package com.atguigu.gmall.payment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.AlipayService;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: lx
 * @Time: 14:38
 * @Description:
 */
@Service
public class AlipayServiceImpl  implements AlipayService {


    @Autowired
    private PaymentService paymentService;
    @Autowired
    private AlipayClient alipayClient;

    //调用支付宝公司的接口
    @Override
    public String submitAlipay(Long orderId) {
        //1:生成支付表
        PaymentInfo paymentInfo = paymentService.insert(orderId);
        //2:调用支付宝公司的接口
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        Map map = new HashMap<>();
        map.put("out_trade_no",paymentInfo.getOutTradeNo());
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        map.put("total_amount",paymentInfo.getTotalAmount());
        map.put("subject",paymentInfo.getSubject());
        //将来如果成功了
        //同步通知  页面转发
        request.setReturnUrl(AlipayConfig.return_payment_url);
        //异步通知  支付成功
        request.setNotifyUrl(AlipayConfig.notify_payment_url);
        request.setBizContent(JSONObject.toJSONString(map));
        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){

            String body = response.getBody();//
            System.out.println(body);
            System.out.println("调用成功");
            return body;
        } else {
            System.out.println("调用失败");
        }
        return null;
    }
    //退钱

}
